package org.compiere.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import extend.org.compiere.utils.Util;

public class Mhrmorder extends X_hrm_order {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -200993871442852238L;
	
	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (Mhrmorder.class);
	
	/**	Employee Lines	*/
	private Mhrmemployee[] m_lines;
	private Mhrmemployeessigned[] linesSigned;

	public Mhrmorder(Properties ctx, int hrm_order_ID, String trxName) {
		super(ctx, hrm_order_ID, trxName);
	}
	
	public Mhrmorder(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}
	
	/**
	 * 	Get HR Employee Lines of Order
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private Mhrmemployee[] getLinesEmployee (String whereClause)
	{
		String whereClauseFinal = "hrm_order_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<Mhrmemployee> list = new Query(getCtx(), I_hrm_employee.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_order_ID())
										.list();
		return list.toArray(new Mhrmemployee[list.size()]);
	}	//	getLines

	/**
	 * 	Get Order Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public Mhrmemployee[] getLinesEmployee (boolean requery)
	{
		if (m_lines == null || m_lines.length == 0 || requery)
			m_lines = getLinesEmployee(null);
		set_TrxName(m_lines, get_TrxName());
		return m_lines;
	}	//	getLines

	/**
	 * 	Get Lines of HR Order
	 * 	@return lines
	 */
	public Mhrmemployee[] getLinesEmployee()
	{
		return getLinesEmployee(false);
	}	//	getLines
	
	/**
	 * 	Get signatures of the order
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private Mhrmemployeessigned[] getLinesSigned (String whereClause)
	{
		String whereClauseFinal = "hrm_order_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<Mhrmemployeessigned> list = new Query(getCtx(), I_hrm_employeessigned.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_order_ID())
										.list();
		return list.toArray(new Mhrmemployeessigned[list.size()]);
	}	//	getLinesSigned

	/**
	 * 	Get Order Lines signed
	 * 	@param requery
	 * 	@return lines
	 */
	public Mhrmemployeessigned[] getLinesSigned (boolean requery)
	{
		if (linesSigned == null || linesSigned.length == 0 || requery)
			linesSigned = getLinesSigned(null);
		set_TrxName(linesSigned, get_TrxName());
		return linesSigned;
	}	//	getLinesSigned

	/**
	 * 	Get Signed of HR Order
	 * 	@return lines
	 */
	public Mhrmemployeessigned[] getLinesSigned()
	{
		return getLinesSigned(false);
	}	//	getLinesSigned
	
	// Error message
	private StringBuilder errmsg = new StringBuilder();
	
	//** check whether the given period */
	private void checkPeriodBase(){

		//
		if(getStartDate() == null 
				&& getEndDate() == null
				&& (gethrm_ordertype().equals(HRM_ORDERTYPE_BusinessTrip)
				|| gethrm_ordertype().equals(HRM_ORDERTYPE_Moving)
				|| gethrm_ordertype().equals(HRM_ORDERTYPE_Vacation))) {
			errmsg.append(Msg.translate(getCtx(), "NotSelectedPeriod")).append("\n");
			return;
		}
		//
		if(getStartDate() == null) 
			errmsg.append(Util.requiredField(COLUMNNAME_StartDate)).append("\n");
		else if(getEndDate() == null
				&& (gethrm_ordertype().equals(HRM_ORDERTYPE_BusinessTrip)
						|| gethrm_ordertype().equals(HRM_ORDERTYPE_Vacation))) 
			errmsg.append(Util.requiredField(COLUMNNAME_EndDate)).append("\n");
	}
	
	@Override
	protected boolean beforeSave(boolean newRecord) {
		
		// perform the test parentally
		super.beforeSave(newRecord);
		
		//hiring
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_Hiring)){
			checkPeriodBase();
			if(gethrm_departmentTo_ID()==0) errmsg.append(Util.requiredField(COLUMNNAME_hrm_departmentTo_ID)).append("\n");
			if(gethrm_tojob_ID()==0) errmsg.append(Util.requiredField(COLUMNNAME_hrm_tojob_ID));
			Util.checkErrMsg(errmsg);
		}
		//vacation
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_Vacation)){
			checkPeriodBase();
			if(gethrm_workleavetype() == null ) errmsg.append(Util.requiredField(COLUMNNAME_hrm_workleavetype)).append("\n");
			Util.checkErrMsg(errmsg);
		}
		// Business Trip
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_BusinessTrip)){
			checkPeriodBase();
			if(gethrm_purpose() == null || gethrm_purpose().isEmpty()) errmsg.append(Util.requiredField(COLUMNNAME_hrm_purpose)).append("\n");
			if(gethrm_businesstriptype() == null) errmsg.append(Util.requiredField(COLUMNNAME_hrm_businesstriptype)).append("\n");
			if(gethrm_whereto_ID() == 0) errmsg.append(Util.requiredField(COLUMNNAME_hrm_whereto_ID)).append("\n");
			// TODO if(gethrm_transporttype() == null) errmsg.append(Utils.requiredField(COLUMNNAME_hrm_transporttype)).append("\n");
			Util.checkErrMsg(errmsg);
			
		}
		// Dismissal
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_Dismissal)){
			checkPeriodBase();
			if(gethrm_contractterminationtype() == null) errmsg.append(Util.requiredField(COLUMNNAME_hrm_contractterminationtype)).append("\n");
			Util.checkErrMsg(errmsg);
		}
		// Stoppage Of Wages
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_StoppageOfWages)){
			checkPeriodBase();
			// TODO if(getAmount() == 0) errmsg.append(Utils.requiredField(COLUMNNAME_Amount)).append("\n");
			Util.checkErrMsg(errmsg);
		}
		// Premium
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_Premium)){
			checkPeriodBase();
			// TODO if(getAmount() == 0) errmsg.append(Utils.requiredField(COLUMNNAME_Amount)).append("\n");
			Util.checkErrMsg(errmsg);
		}
		// Moving
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_Moving)){
			checkPeriodBase();
			Util.checkErrMsg(errmsg);
		}
		// Withholding
		if(gethrm_ordertype().equals(X_hrm_order.HRM_ORDERTYPE_StoppageOfWages)){
			if(getAmount().intValue() > 0 && gethrm_percent().intValue()> 0.){
				errmsg.append("Заполните только одно из полей. \n"+  Msg.translate(Env.getCtx(), "Field")+": "+Msg.translate(Env.getCtx(), COLUMNNAME_Amount)+", ");
				errmsg.append(Msg.translate(Env.getCtx(), COLUMNNAME_hrm_percent)+" \n");
				Util.checkErrMsg(errmsg);
			}
		}
		
		
		return true;
	}
	
	@Override
	protected boolean afterSave(boolean newRecord, boolean success) {
		
		if(newRecord){
			Mhrmemployeessigned hrmsign = null;
			MBPartner[] bp = Mhrmemployeessigned.getSigningBPartner();
			for(MBPartner b: bp){
				hrmsign = new Mhrmemployeessigned(getCtx(), 0, get_TrxName());
				hrmsign.sethrm_order_ID(get_ID());
				hrmsign.setC_BPartner_ID(b.getC_BPartner_ID());
				hrmsign.saveEx();
			}
		}
		
		return success;
	}
	
	/**
	 * 	Update Record directly
	 * 	@return true if updated
	 */
	public boolean saveUpdate() {
		return super.saveUpdate();
	}
	
	public static Mhrmorder getOrderRec(int hrm_order_ID, Timestamp sdt, Timestamp edt, String atype){
		//	
	    PreparedStatement pstmt = null;
		ResultSet rs = null;
		Mhrmorder result = null;			
		// 
		String sql_ = "SELECT * FROM HRM_ORDER \n" +
						 "WHERE ISACTIVE='Y' \n" +
							"AND AD_CLIENT_ID="  + Env.getAD_Client_ID(Env.getCtx()) + " \n" +							
							"AND HRM_ORDER_ID="  + hrm_order_ID    + " \n" +
							"AND STARTDATE >="   + DB.TO_DATE(sdt) + " \n" +
							"AND ENDDATE <="     + DB.TO_DATE(edt) + " \n" +
							"AND HRM_ORDERTYPE='" + atype           + "' \n" ;							
			try
			{
				pstmt = DB.prepareStatement(sql_,null);				
				rs = pstmt.executeQuery();	
				if(rs.next())
					result = new Mhrmorder(Env.getCtx(), rs, null);
			}
			catch (SQLException e)
			{
				s_log.log(Level.SEVERE, "product", e);
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}	
		return result;		
	}
	
	public static Mhrmorder getOrderFromDate(int hrm_order_ID, Timestamp dt, String atype){
		//	
	    PreparedStatement pstmt = null;
		ResultSet rs = null;
		Mhrmorder result = null;			
		// 
		String sql_ = "SELECT * FROM HRM_ORDER \n" +
						 "WHERE ISACTIVE='Y' \n"   +
							" AND AD_CLIENT_ID="   + Env.getAD_Client_ID(Env.getCtx()) + " \n" +							
							" AND HRM_ORDER_ID="   + hrm_order_ID    + " \n" +
							" AND DATEFROM ="      + DB.TO_DATE(dt)  + " \n" +							
							" AND HRM_ORDERTYPE='" + atype           + "'  " ;							
			try
			{
				pstmt = DB.prepareStatement(sql_,null);				
				rs = pstmt.executeQuery();	
				if(rs.next())
					result = new Mhrmorder(Env.getCtx(), rs, null);
			}
			catch (SQLException e)
			{
				s_log.log(Level.SEVERE, "product", e);
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}
			
		return result;		
	}
	
	public static String getOrderName(int hrm_order_ID, String atype){
		//	
	    PreparedStatement pstmt = null;
		ResultSet rs = null;
		String result = null;			
		// 
		String sql_ = "SELECT * FROM HRM_ORDER \n" +
						 "WHERE ISACTIVE='Y' \n" +
							"AND AD_CLIENT_ID="  + Env.getAD_Client_ID(Env.getCtx()) + " \n" +							
							"AND HRM_ORDER_ID="  + hrm_order_ID    + " \n" +
							"AND HRM_ORDERTYPE='" + atype          + "' \n" ;							
			try
			{
				pstmt = DB.prepareStatement(sql_,null);				
				rs = pstmt.executeQuery();	
				if(rs.next())
					return rs.getString(1);
			}
			catch (SQLException e)
			{
				s_log.log(Level.SEVERE, "product", e);
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}	
		return result;		
	}
	//--add by A.Kulantayev  Description: method return hrm_order list of BP
	public static Mhrmorder[] getHRMOrderList(String hrm_ordertype, int C_BPartner_ID){
		Mhrmorder vacLine = null;
    	List<Mhrmorder> list = new ArrayList<Mhrmorder>();
	    PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM HRM_Order WHERE AD_Client_ID = ? AND HRM_OrderType = ? AND HRM_Order_ID IN " +
				"(SELECT HRM_Order_ID FROM HRM_Employee WHERE Processed = 'Y' AND C_BPartner_ID = ?);";
		try{
			pstmt = DB.prepareStatement(sql,null);
			pstmt.setInt(1, Env.getAD_Client_ID(Env.getCtx()));
			pstmt.setString(2, hrm_ordertype);
			pstmt.setInt(3, C_BPartner_ID);
			rs = pstmt.executeQuery();
			while(rs.next()){
				vacLine = new Mhrmorder(Env.getCtx(), rs, null);
				list.add(vacLine);
				vacLine = null;
				int a = 1+1;
			}
		} catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "HRM_Order", e);
		}finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}	
		return list.toArray(new Mhrmorder[list.size()]);
	}
	//--
}
